import { Message } from 'element-ui'
import router from '../router/index'
import store from '../store/index'
import Auth from './auth'

router.beforeEach(async (to, from, next) => {
  if (Auth.getToken()) {
    if (to.path === '/login') {
      return next('/')
    } else {
      const hasRoles = !!store.getters.roles
      if (hasRoles) {
        next()
      } else {
        try {
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const roles = await store.dispatch('user/getInfo')
          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (err) {
          await store.dispatch('user/resetToken')
          Message({
            message: err || 'Error',
            type: 'error',
            duration: 5 * 1000
          })
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (to.path === '/login') return next()
    next('/login')
  }
})
